package woa.binarysearch;

/**
 * @author wangpeng
 * @date 2023/8/1 10:33
 */
public class BinarySearchTest {

    public static int searchEqualWithNoRepeat(int[] nums, int t) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (t == nums[m]) {
                return m;
            }
            if (t > nums[m]) {
                l = m + 1;
            } else {
                h = m - 1;
            }
        }

        return -1;
    }

    public static int searchFirstEqual(int[] nums, int t) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (t == nums[m]) {
                if (m == l || t != nums[m - 1]) {
                    return m;
                }
                h = m - 1;
            } else if (t < nums[m]) {
                h = m - 1;
            } else {
                l = m + 1;
            }
        }

        return -1;
    }

    public static int searchLastEqual(int[] nums, int t) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (t == nums[m]) {
                if (m == h || t != nums[m + 1]) {
                    return m;
                }
                l = m + 1;
            } else if (t < nums[m]) {
                h = m - 1;
            } else {
                l = m + 1;
            }
        }

        return -1;
    }

    public static int searchFirstGtEqual(int[] nums, int t) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (t <= nums[m]) {
                if (m == l || t > nums[m - 1]) {
                    return m;
                }
                h = m - 1;
            } else {
                l = m + 1;
            }
        }

        return -1;
    }

    public static int searchLastLtEqual(int[] nums, int t) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (t >= nums[m]) {
                if (m == h || t < nums[m + 1]) {
                    return m;
                }
                l = m + 1;
            } else {
                h = m - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {1,2,2,4,5,6};
        System.out.println(searchLastLtEqual(nums, 6));
    }
}
